package com.bilibili.sys.servlet;

import com.bilibili.sys.bean.SysRole;
import com.bilibili.sys.service.IRoleService;
import com.bilibili.sys.service.impl.RoleServiceImpl;
import com.bilibili.sys.utils.Constant;
import com.bilibili.sys.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author alpha
 * @program: BookSystem
 * @description:
 * @since 2024-03-28 08:46
 **/
@WebServlet(name="roleServlet",urlPatterns = {"/sys/roleServlet"})
public class RoleServlet extends BaseServlet{
    private IRoleService service = new RoleServiceImpl();
    @Override
    public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        super.list(req, resp);//封装了分页的相关操作
        //TODO 写我们自己的查询处理
        service.listPage(pageUtils);
        req.setAttribute(Constant.LIST_PAGE_UTILS,pageUtils);
        //页面跳转
        req.getRequestDispatcher("/sys/role/list.jsp").forward(req,resp);
    }

    @Override
    public void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取提交的数据
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String notes = req.getParameter("notes");
        SysRole entity = new SysRole();
        entity.setNotes(notes);
        entity.setName(name);
        if(StringUtils.isNotEmpty(id)){
            //更新
            entity.setId(Integer.parseInt(id));
            service.updateById(entity);
        }else{
            //保存数据
            service.save(entity);
        }
        //做重定向查询
        resp.sendRedirect("/sys/roleServlet?action=list");

    }

    @Override
    public void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //删除角色信息
        String id = req.getParameter("id");
        //删除role时需要做校验，如果该角色已经分配给了用户，那么这个角色就不能被删除
        boolean flag= service.checkRoleDispatch(Integer.parseInt(id));
        PrintWriter writer = resp.getWriter();
        if(flag){
            //表示没有被分配 可以删除
            service.deleteById(Integer.parseInt(id));
            writer.write("ok");
        }else{
            //表示不能被删除
            writer.write("error");
        }
        writer.flush();
        writer.close();
    }

    @Override
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    }

    @Override
    public void saveOrUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //如果是更新，需要查询出数据库中当前最新的信息
        String id = req.getParameter("id");
        if(StringUtils.isNotEmpty(id)){
            //说明是更新
            SysRole entity = service.findById(Integer.parseInt(id));
            req.setAttribute("entity",entity);
        }
        req.getRequestDispatcher("/sys/role/addOrUpdate.jsp").forward(req,resp);
    }
}
